#pragma once

#include <iostream>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace std;

#define PATHNAME "."
#define PROJID 0x6666

#define SERVER 1
#define CLIENT 0


const int gsize = 4096;

key_t getKey()
{
    key_t k = ftok(PATHNAME,PROJID);
    if(k == -1)
    {
        cerr << "error" << errno << ":" << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

int createShmHelper(key_t k,int size,int flag)
{
    int shmid = shmget(k,gsize,flag);
    if(shmid == -1)
    {
        cerr << "error" << errno << ":" << strerror(errno) << endl;
    }
    return shmid;
}

int createShm(key_t k,int size)
{
    umask(0);
    // IPC_CREAT | IPC_EXCL 创建一个共享内存，如果其不存在就创建，如果存在直接报错
    // 这样保证了每次获得的共享内存都是最新的
    return createShmHelper(k,size,IPC_CREAT | IPC_EXCL | 0666);
}

int getShm(key_t k,int size)
{
    // IPC_CREAT 创建一个共享内存，若不存在就创建，若存在返回已经获取的共享内存
    return createShmHelper(k,size,IPC_CREAT);
}

char* attachShm(int shmid)
{
    char* start = (char*)shmat(shmid,nullptr,0);
    return start;
}

void detachShm(char* start)
{
    int n = shmdt(start);
    assert(n != -1);
    (void)n;
}

void delShm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
}

class Init
{
public:
    Init(int t) : type(t)
    {
        key_t k = getKey();
        if(type == SERVER) shmid = createShm(k,gsize);
        else shmid = getShm(k,gsize);

        start = attachShm(shmid);
    }
    ~Init()
    {
        detachShm(start);
        if(type == SERVER) delShm(shmid);
    }
    char* getStart()
    {
        return start;
    }
private:
    char* start;
    int type;//server or client
    int shmid;
};